package com.howlaisi.sms.student.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.howlaisi.sms.student.form.StudentForm;
import com.howlaisi.sms.student.mapper.StudentMapper;
import com.howlaisi.sms.student.pojo.bo.StudentBO;
import com.howlaisi.sms.student.pojo.converter.StudentConverter;
import com.howlaisi.sms.student.pojo.entity.StudentEntity;
import com.howlaisi.sms.student.pojo.query.StudentPageQuery;
import com.howlaisi.sms.student.pojo.vo.StudentVO;
import com.howlaisi.sms.student.service.StudentService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 张师傅
 * @date 2024/6/27
 */

@Service
@RequiredArgsConstructor
public class StudentServiceImpl extends ServiceImpl<StudentMapper, StudentEntity> implements StudentService {

    private final StudentConverter studentConverter;

    @Override
    public IPage<StudentVO> listStudentPages(StudentPageQuery queryParams) {
        // 查询数据
        Page<StudentBO> studentBoPage = this.baseMapper.listStudentPages(
                new Page<>(queryParams.getPageNum(),
                        queryParams.getPageSize()),
                queryParams
        );

        // 实体转换
        Page<StudentVO> studentVoPage = studentConverter.boPage2VoPage(studentBoPage);

        return studentVoPage;
    }

    @Override
    public boolean saveStudent(StudentForm form) {
        StudentEntity studentEntity = studentConverter.form2Entity(form);
        return this.saveOrUpdate(studentEntity);
    }

    @Override
    public boolean deleteStudents(String idsStr) {
        Assert.isTrue(StrUtil.isNotBlank(idsStr), "删除的用户数据为空");

        // 将字符串转换为Long类型的ID列表
        List<Long> ids = Arrays.stream(idsStr.split(","))
                .map(Long::parseLong)
                .collect(Collectors.toList());

        // 创建LambdaUpdateWrapper来构建更新条件
        LambdaUpdateWrapper<StudentEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(StudentEntity::getId, ids)
                .set(StudentEntity::getDeleted, 1);

        // 执行更新操作
        int affectedRows = this.baseMapper.update(null, updateWrapper);

        // 根据受影响的行数来判断是否成功（通常大于0表示成功）
        return affectedRows > 0;
    }

    @Override
    public boolean updateStudent(StudentForm form) {
        // form -> entity
        StudentEntity studentEntity = studentConverter.form2Entity(form);

        // 修改学生
        return this.updateById(studentEntity);
    }
}
